/**
 * Created by Ray on 2017/9/14.
 */
'use strict';
var router = require('express').Router();
var AV = require('leanengine');
var tribeTools = require('../queryFun/tribeTools');
var functionTool = require('../queryFun/functionTool');
var Todo = AV.Object.extend('Todo');
var qn = require('../qiniu/upload');
var upload = require('../queryFun/fileuploads');
// var qiniuServer   = require( '../cloud/server/qiniuServer' );
var fs = require('fs');
var path = process.cwd();
var uuid = require('node-uuid');
var fs = require("fs");
let qiniu = require("qiniu");
router.post('/tribeMGTree', function (req, res) {
    tribeTools.tribeType(function (result) {
        res.send(JSON.stringify(result));
    })
});

router.post('/tribeMG', function (req, res, next) {
    var type = req.body.dept_id;
    var name = req.body.name;
    var objectId = req.body.objectId;
    var creater = req.body.creater;
    var nickName = req.body.nickName;
    var page = req.body.pageIndex;
    var num = req.body.pageSize;
    var numNumber = req.body.numNumber;
    tribeTools.getTribeInformationForCategory(objectId, name, creater, nickName, type, numNumber, page, num, function (err, result) {
        res.send(JSON.stringify(result));
    })
});

router.get('/regTribeAdd', function (req, res) {
    res.render("reg/regSelect")
})

router.post('/regTribeFind', async function (req, res) {
    let tribeName = req.body.name;
    let tribeId = req.body.objectId;
    let page = req.body.pageIndex;
    let num = req.body.pageSize;
    let result = await tribeTools.getRegTribeFind(tribeId, tribeName, page, num)
    res.send(JSON.stringify(result))

})

router.post('/regTribeDefault', async function (req, res) {
    let page = req.body.pageIndex;
    page = Number(page) + 1;
    let num = req.body.pageSize;
    let result = await  tribeTools.getRegTribeDefault(page, num);
    res.send(JSON.stringify(result));
})

router.post('/regTribeRemove',async function(req,res){
    let objectId = req.body.objectId;
    let result = await  tribeTools.regTribeRemove(objectId);
    res.send(JSON.stringify(result));
})


router.get('/tribeAdd', function (req, res) {
    res.render("tribe/tribeSelect")
})
router.post('/tribeFind', async function (req, res) {
    let tribeName = req.body.name;
    let tribeId = req.body.objectId;
    let page = req.body.pageIndex;
    let num = req.body.pageSize;
    let result = await tribeTools.getTribeFind(tribeId, tribeName, page, num)
    res.send(JSON.stringify(result))
})


//tribeBonus
router.post('/tribeBonus',async function (req,res) {
    let page = req.body.pageIndex;
    // page = Number(page) + 1;
    // let num = req.body.pageSize;
    // let result = await tribeTools.getTribe(page,num);
    // res.send(JSON.stringify(result));
  var params = {};
  params.page = Number(page) + 1;;
  params.num = req.body.pageSize;
  params.name = req.body.name;
  params.objectId = req.body.objectId;
  params.creater = req.body.creater;
  params.nickName = req.body.nickName;
  params.numNumber = req.body.numNumber;
  let result = await tribeTools.getTribe(params);
  res.send(JSON.stringify(result));
  // tribeTools.getTribe(params, function (result) {
  //   // console.log(JSON.stringify(result));
  //   res.send(JSON.stringify(result));
  // })

})

router.get('/tribeBonusEdit', async function (req, res) {
    let objectId = req.query.objectId;
    let result = await  tribeTools.getSelTribe(objectId);
    res.render('tribe/tribeBonusEdit', {result: result})
})

router.post('/tribePossibleBonus',async function (req,res) {
    let objectId = req.body.objectId;
    let possibleBonus = req.body.possibleBonus;
    if(possibleBonus=='不可加分'){
        possibleBonus = '0';
    }else if(possibleBonus=='可加分'){
        possibleBonus = '1';
    }
    let maxNum = req.body.maxNum;
    maxNum = Number(maxNum);
    let result = await  tribeTools.updateTribePossible(objectId,possibleBonus,maxNum);
    if(result){
        res.send("1");
    }else{
        res.send("0");
    }

})
router.get('/tribeBonusAdd', function (req, res) {
  res.render("tribe/tribeBonusAdd")
})
router.post('/tribeBonusAdd', async function (req, res) {
  let objectId = req.body.objectId;
  let result = await  tribeTools.tribeBonusAdd(objectId);
  res.render('tribe/tribeBonusAdd', {result: result})
})
router.post('/tribeBonusRemove', function (req, res) {
  var objectId = req.body.objectId;
  tribeTools.tribeBonusRemove(objectId, function (result) {
    // console.log(result);
    res.send(result);
  })
})
router.get('/tribeMGAdd', function (req, res) {
    tribeTools.tribeCategory(function (tribeCategory) {
        var result = {};
        result.tribeCategory = tribeCategory;
        // console.log(tribeCategory)
        res.render("tribe/tribeMGAdd", {tribeCategory: JSON.stringify(tribeCategory)});
    })
});

router.post('/findRegTribe', async function (req, res) {
    let objectId = req.body.objectId;
    let result = await  tribeTools.findRegMember(objectId);
    res.send(JSON.stringify(result));
})

router.post('/findTribeMember', async function (req, res) {
    let objectId = req.body.objectId;
    let result = await  tribeTools.findTribeMember(objectId);
    res.send(JSON.stringify(result));
})

router.post('/insertRegTribeDefault', async function (req, res) {
    let objectId = req.body.objectId;
    let result = await  tribeTools.insertRegTribeDefault(objectId);
    res.send(JSON.stringify(result));
})

router.post('/insertTribeMember', async function (req, res) {
    let result = await  tribeTools.insertTribeMember(req);
    res.send(JSON.stringify(result));
})


//添加音频
router.get('/addAudio', function (req, res) {
    let objectId = req.query.objectId;
    let config = qn.config;
    let options = {
        scope: config.Bucket,
        deleteAfterDays: 0,
        deadline: Date.now() / 1000 + 3600,
        persistentOps: 'avthumb/mp3/ab/256k;avthumb/m3u8/segtime/15',
        persistentNotifyUrl: "http://tribe.aladada.com/qiniuPersistentAudioSuccess",
        persistentPipeline: "duilie1"
    };
    let putPolicy = new qiniu.rs.PutPolicy(options);
    let mac = new qiniu.auth.digest.Mac(config.AccessKey, config.SecretKey);
    let token = putPolicy.uploadToken(mac);

    res.render('tribe/tribeAudioAdd', {
        domain: config.Domain,
        uptoken: token,
        objectId: objectId
    })
})
//添加视频
router.get('/addMedia', function (req, res) {
    let objectId = req.query.objectId;
    let config = qn.config;
    let options = {
        scope: config.Bucket,
        deleteAfterDays: 0,
        deadline: Date.now() / 1000 + 3600,
        persistentOps: "avthumb/mp4/vb/640k;vframe/jpg/offset/0.001/w/400/h/440;avthumb/m3u8/segtime/5/preset/video_640k/rotate/90",
        persistentNotifyUrl: "http://tribe.aladada.com/qiniuPersistentMediaSuccess",
        persistentPipeline: "duilie1"
    };
    let putPolicy = new qiniu.rs.PutPolicy(options);
    let mac = new qiniu.auth.digest.Mac(config.AccessKey, config.SecretKey);
    let token = putPolicy.uploadToken(mac);

    res.render('tribe/tribeMediaAdd', {
        domain: config.Domain,
        uptoken: token,
        objectId: objectId
    })
})

router.post('/updateMediaAudio', async function (req, res) {

    req.params = req.body;
    let result = await  tribeTools.updateThreadAudio(req);
    console.log(result, "result======")
    if (result) {
        res.send("10000");
    } else {
        res.send("10001");

    }
})

router.post('/updateMedia', async function (req, res) {

    req.params = req.body;
    let result = await  tribeTools.updateThreadMedia(req);

    if (result) {
        res.send("10000");
    } else {
        res.send("10001");

    }
})


router.get('/tribeMGEditSelectCreater', function (req, res) {
    res.render("tribe/tribeMGEditSelectCreater");
});

router.post('/tribeMGEditSelectCreaterData', function (req, res) {
    var nickName = req.body.nickName;
    var page = req.body.pageIndex;
    var num = req.body.pageSize;
    var username = req.body.username;
    functionTool.userInformation(nickName, '', '', '', page, num,username,function (err, result) {
        // res.render("tribe/tribeMGEditSelectCreater",{result:JSON.stringify(result)});
        res.send(JSON.stringify(result));
    })
});
router.post('/checkTribeNameIsUsable', function (req, res) {
    // console.log(req.body.name);
    var tribeName = req.body.name;
    tribeTools.checkTribeNameIsUsable(tribeName, function (result) {
        res.send(result);
    })
});
router.post('/imageUpload', upload.single('image'), function (req, res, next) {
    var uploadFilePath = req.file.path;
    var filename = req.file.filename;
    if (req.file) {
        fs.readFile(uploadFilePath, function (err, data) {
            // console.log(err);
            // console.log(data);
            var file = new AV.File(filename, data);
            file.save().then(function (file) {
                // 文件保存成功
                // console.log(file.url());
                // console.log(file.id);

                fs.unlink(uploadFilePath, function (error) {
                    if (error) {
                        console.log(error);
                    } else {
                        // console.log('文件:'+uploadFilePath+'删除成功！');
                    }
                })

                var tribeAvator = file.id;
                var reqData = {};
                var user = {};
                var params = {};
                user.id = req.body.createrId;
                user.nickName = req.body.createrName;
                reqData.user = user;
                params.tribeAvator = tribeAvator;
                params.name = req.body.name;
                params.category = req.body.category;
                params.capacity = req.body.capacity;
                params.isPublic = req.body.isPublic;
                params.status = req.body.status;
                params.verify = req.body.verify;
                params.verifyCost = req.body.verifyCost;
                params.generalize = req.body.generalize;
                params.introduction = req.body.introduction;
                reqData.params = params;

                // console.log(JSON.stringify(reqData));

                tribeTools.createTribe(reqData, function (result) {
                    // console.log("------"+JSON.stringify(result));
                    res.end(result);
                })
            }, function (error) {
                // 异常处理
                console.error(error);
            });
        });
    } else {
        console.log('文件不存在')
    }
});

router.get('/tribeMGEdit', function (req, res) {
    var objectId = req.query.id;
    tribeTools.getTribeInformationForCategory(objectId, '', '', '', '', '', '', '', function (err, result) {

        tribeTools.tribeCategory(function (tribeCategory) {
            result.tribeCategory = JSON.stringify(tribeCategory);
            // console.log(result.tribeMGTree);
            res.render("tribe/tribeMGEdit", {result: result});
        })
    });
});
router.post('/updateTribeInfo', function (req, res) {
    req.params = req.body;
    tribeTools.updateTribeInfo(req, function (error, result) {
        res.send();
    })
});
router.post('/tribeMGRemove', function (req, res) {
  var objectId = req.body.objectId;
  tribeTools.removeTribe(objectId, function (result) {
    // console.log(result);
    res.send(result);
  })
})
router.post('/tribeMGRecommendRemove', function (req, res) {
    var objectId = req.body.objectId;
    tribeTools.recommendTribeRemove(objectId, function (result) {
        // console.log(result);
      if (result == objectId){
        res.send(result);
      } else {
        res.send();
      }
    })
})
router.get('/tribeMGSort', function (req, res) {
    // console.log(req)
    res.render("tribe/tribeMGSort", {});
});
router.post('/tribeMGSortHandle', function (req, res) {
    // console.log(req.body);
    var params = req.body;
    tribeTools.tribeMGSortHandle(params, function (result) {
        // console.log(result);
        res.send(result);
    })

});
router.post('/getTribeMembersInfo', function (req, res) {
    var tribeOId = req.body.tribeOId;
    var userOId = req.body.userOId;
    var userType = req.body.userType;
    var nickName = req.body.nickName;
    var page = req.body.pageIndex;
    var num = req.body.pageSize;
    var params = {};
    params.tribeOId = tribeOId;
    params.page = page;
    params.num = num;
    params.userOId = userOId;
    params.userType = userType;
    params.nickName = nickName;
    tribeTools.getTribeMembers(params, function (result) {
        // console.log(JSON.stringify(result));
        res.send(result);
    })
});

router.get('/tribeMemberAdd', function (req, res) {
    var tribeOId = req.query.tribeOId;
    var tribeName = req.query.tribeName;
    var result = {};
    result.tribeOId = tribeOId;
    result.tribeName = tribeName;
    res.render("tribe/tribeMemberAdd", {result: result});

});

router.post('/checkTribeMember', function (req, res) {
    var tribeOId = req.body.tribeOId;
    var userOId = req.body.userOId;
    var data = {};
    data.tribeOId = tribeOId;
    data.userOId = userOId;
    tribeTools.checkTribeMember(data, function (result) {
        res.send(result);
    })
});
router.post('/addTribeMember', function (req, res) {

    var currentUser = req.currentUser;
    if (currentUser == '' || currentUser == undefined || currentUser == null) {
        console.log('无法获取currentUser')
        res.send(JSON.stringify('请重新登录'));
    } else {
        // console.log(currentUser.id);
        var handler = currentUser.id;
        var tribeOId = req.body.tribeOId;
        var userOId = req.body.userOId;
        var userType = req.body.userType;
        var data = {};
        data.tribeOId = tribeOId;
        data.userOId = userOId;
        data.userType = userType;
        data.handler = handler;
        // console.log(data);
        tribeTools.addTribeMember(data, function (result) {
            res.send(result);
        })
    }

});

router.post('/manuAddTribeMember', function (req, res) {

    // var currentUser = req.currentUser;
    // if (currentUser==''||currentUser==undefined||currentUser==null) {
    //     console.log('无法获取currentUser')
    //     res.send(JSON.stringify('请重新登录'));
    // } else {
    // console.log(currentUser.id);
    var handler = '5a198372ac502e005e577889';
    var tribeOId = req.body.tribeOId;
    var userOId = req.body.userOId;
    var userType = req.body.userType;
    var data = {};
    data.tribeOId = tribeOId;
    data.userOId = userOId;
    data.userType = userType;
    data.handler = handler;
    // console.log(data);
    tribeTools.addTribeMember(data, function (result) {
        res.send(result);
    })
    // }

});


router.get('/tribeMemberEdit', function (req, res) {
    // console.log(req)
    res.render("tribe/tribeMemberEdit", {});
});
router.post('/tribeMemberEditHandle', function (req, res) {
    // console.log(req.body);
    var params = req.body;
    tribeTools.tribeMemberEditHandle(params, function (result) {
        // console.log(result);
        res.send(result);
    })
});

router.post('/tribeThreadMG', function (req, res, next) {
    var params = {};
    var page = req.body.pageIndex;
    var num = req.body.pageSize;
    var objectId = req.body.objectId;
    var tribeOId = req.body.tribeOId;
    var tribeName = req.body.tribeName;
    var creater = req.body.creater;
    var nickName = req.body.nickName;
    var threadContent = req.body.threadContent;
    var status = req.body.status;
    params.page = page;
    params.num = num;
    params.objectId = objectId;
    params.tribeOId = tribeOId;
    params.tribeName = tribeName;
    params.creater = creater;
    params.nickName = nickName;
    params.threadContent = threadContent;
    params.status = status;
    // console.log(params);
    tribeTools.getThreadInfo(params, function (result) {
        res.send(result);
    });
});
router.get("/tribeThreadPlayer", function (req, res) {
    var resultObj = {};
    var objectId = req.query.objectId;
    resultObj.objectId = objectId;
    res.render('tribe/tribeThreadPlayer', {result: resultObj})
});

router.post('/tribeThreadUpdate', function (req, res, next) {
    var params = {};
    var objectId = req.body.objectId;
    var status = req.body.status;
    var isShare = req.body.isShare;
    var content = req.body.content;
    params.objectId = objectId;
    params.status = status;
    params.isShare = isShare;
    params.content = content;
    console.log(req.body);
    tribeTools.updateThreadInfo(params, function (result) {
        res.send(result);
    });
});

router.post('/sync/parentTribe', function (req, res, next) {
    var page = req.body.pageIndex;
    var num = req.body.pageSize;
    var name = req.body.name;
    var relationTribeOId = req.body.relationTribeOId;
    tribeTools.syncParentTribe(name, relationTribeOId, page, num, function (err, result) {
        res.send(JSON.stringify(result));
    })
});

router.get('/relation/tribe', function (req, res, next) {
    var tribeOId = req.query.id;
    res.render("tribe/sync/relation", {tribeOId: tribeOId})
});

router.post('/relation/tribe', function (req, res, next) {
    var parentRelationTribeOId = req.body.parentRelationTribeOId;
    var page = req.body.pageIndex;
    var num = req.body.pageSize;
    var tribeOId = req.body.tribeOId;
    var name = req.body.name;
    tribeTools.syncChildTribe(parentRelationTribeOId, tribeOId, name, page, num, function (err, result) {
        res.send(JSON.stringify(result));
    })
});

router.post('/relation/delete', function (req, res, next) {
    var parentRelationTribeOId = req.body.parentRelationTribeOId;
    var tribeOId = req.body.tribeOId;
    tribeTools.deleteSyncTribe(tribeOId, parentRelationTribeOId, function (err, result) {
        if (!err) {
            res.send("1")
        } else {
            res.send("0")
        }
    })
});

router.get('/relation/otherTribe', function (req, res) {
    var tribeOId = req.query.id;
    res.render("tribe/sync/notRelation", {tribeOId: tribeOId})
});

router.post('/notRelation/tribe', function (req, res, next) {
    var parentRelationTribeOId = req.body.parentRelationTribeOId;
    var page = req.body.pageIndex;
    var num = req.body.pageSize;
    var tribeOId = req.body.objectId;
    var name = req.body.name;
    tribeTools.notSyncChildTribe(parentRelationTribeOId, tribeOId, name, page, num, function (err, result) {
        res.send(JSON.stringify(result));
    })
});


router.post('/relation/add', function (req, res, next) {
    var parentRelationTribeOId = req.body.parentRelationTribeOId;
    var tribeOId = req.body.tribeOId;
    tribeTools.addSynchronzationTribe(parentRelationTribeOId, tribeOId, function (err, result) {
        if (!err) {
            if (result == 10001) {
                res.send("1");
            } else {
                res.send("2");
            }
        } else {
            res.send("0")
        }
    })
});

router.post('/child/brand', function (req, res) {
    var page = req.body.pageIndex;
    var num = req.body.pageSize;
    var objectId = req.body.objectId;
    var userOId = req.body.userOId;
    var nickName = req.body.nickName;
    var tribeName = req.body.tribeName;
    var tribeOId = req.body.tribeOId;
    var content = req.body.content;
    var status = "1";


    tribeTools.tribeShareList(objectId, userOId, nickName, tribeName, tribeOId, status, content, page, num, function (err, result) {
        if (err) {
            res.send();
        } else {
            res.send(JSON.stringify(result));
        }
    })
});

router.post("/tribe/userType", (req, res) => {
    let objectId = req.body.objectId;
    let userType = req.body.userType;
    tribeTools.updateTribeUserType(objectId, userType, (err, result) => {
        if (err) {
            res.send("2");
        } else {
            res.send("1");
        }
    })
});

router.post('/child/brand/delete', function (req, res) {
    var objectIds = req.body.id;
    objectIds = objectIds.split("-");
    tribeTools.updateTribeShare(objectIds, function (err, result) {
        if (err) {
            res.send(err);
        } else {
            res.send("10001");
        }
    })
});

router.post('/tribeThread/delete',async function (req, res) {
    var objectIds = req.body.id;
    objectIds = objectIds.split("-");
    await tribeTools.updateTribeThread(objectIds)
    res.send('10000')
});

router.post('/tribeThread/deleteIneffectiveness', function (req, res) {
  var objectIds = req.body.id;
  objectIds = objectIds.split("-");
  tribeTools.deleteIneffectiveness(objectIds, function (err, result) {
    console.log(result);
    if (err) {
      res.send(err);
    } else {
      res.send("10001");
    }
  })
});

router.post('/userTribe/list', function (req, res) {
    var page = req.body.pageIndex;
    var num = req.body.pageSize;
    var nickName = req.body.nickName;
    var userOId = req.body.userOId;

    tribeTools.userTribeList(userOId, nickName, page, num, function (err, result) {
        if (err) {
            res.send();
        } else {
            res.send(JSON.stringify(result));
        }
    })
});

router.post('/tribeCreate/remove', function (req, res) {
    var objectId = req.body.objectId;
    var todo = AV.Object.createWithoutData('Allow_Create_Tribe', objectId);
    todo.destroy().then(function (success) {
        res.send('1');
        // 删除成功
    }, function (error) {
        res.send('2')
        // 删除失败
    });
});
module.exports = router;